
using System.Linq;
using ApiText.Api.Models;
using ApiText.Api.Repository;
using Microsoft.AspNetCore.Mvc;
using ApiText.Api.Params;
using ApiText.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;

namespace ApiText.Api.Controllers
{
    // [Authorize] //这个标识是 请求要求身份验证。 对于需要登录的网页，服务器返回此响应401，添加到这里表示以下所有的的请求都需要先验证
    [ApiController]
    [Route("[controller]")]

    public class UsersController : ControllerBase
    {
        private IConfiguration _configuration;
        private IRepository<Users> _usersRepository;
        private ToKenParameter _toKenParameter;

        public UsersController(IConfiguration configuration, IRepository<Users> usersRepository)
        {
            _configuration = configuration;
            _usersRepository = usersRepository;
            _toKenParameter = _configuration.GetSection("TokenParameter").Get<ToKenParameter>();
        }

  

        //查询所有的用户 http://localhost:5000/Users 
        [HttpGet]
        public dynamic Get()
        {
                 
        // int currentPage=string.IsNullOrWhiteSpace(Request.Query["currentPage"][0].ToString())==true?1:int.Parse(Request.Query["currentPage"][0]);
        // int pageSize=string.IsNullOrWhiteSpace(Request.Query["pageSize"][0].ToString())==true?1:int.Parse(Request.Query["pageSize"][0]);
            var currentPage = int.Parse(Request.Query["currentPage"][0]);  //  1,
            var pageSize = int.Parse(Request.Query["pageSize"][0]);  //   10,
                                                                     //   var  totalSize=Request.Query["totalSize"][0];  //   30,
            var users = _usersRepository.Table.ToList();

            //   分页
            var u = users.Skip((currentPage - 1) * pageSize).Take(pageSize);

            var res = new
            {
                Code = 1000,
                Data = new
                {
                    Data = u,
                    Pager = new { currentPage, pageSize, totalSize = users.Count() }
                },
                Msg = "获取所有用户成功"
            };

            return JsonHelper.Serialize(res);

        }

        [HttpGet("{id}")]
        public dynamic Get(int id)
        {

            //通过id获取指定的用户
            var user = _usersRepository.GetById(id);
            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "当前用户不存在"
                };
            }

            return new
            {
                Code = 1000,
                Data = user,
                Msg = "获取当前用户成功"
            };
        }
        // [AllowAnonymous]
        [HttpPost]
        public dynamic Post(CreateUser newUser)
        {
            var username = newUser.Username.Trim();

            //判断密码是否为空，若为空则设置默认值等于113
            var password = string.IsNullOrEmpty(newUser.Password) ? "113" : newUser.Password.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {

                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "账号或密码不能为空"
                };
            }

            var user = new Users
            {
                Username = username,
                Password = password,
                Remarks = newUser.Remarks
            };

            //将账号密码插入到Users表中
            _usersRepository.Insert(user);

            var res = new
            {
                Code = 1000,
                Data = user,
                Msg = "创建用户成功"
            };

            //将结果实例化后输出
            return JsonHelper.Serialize(res);
        }

        //根据id修改指定信息
        [HttpPut("{id}")]
        public dynamic Put(int id, CreateUser updateUser)
        {
            var username = updateUser.Username.Trim();

            //判断密码是否为空，若为空则设置默认值等于113
            var password = string.IsNullOrEmpty(updateUser.Password) ? "113" : updateUser.Password.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "账号或密码不能为空"
                };
            }


            //通过Id获取要修改的用户
            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "你要更新的用户不存在"
                };
            }


            //将要修改的账号密码重新赋给user
            user.Username = username;
            user.Password = password;
            user.Remarks = updateUser.Remarks;

            //更新数据
            _usersRepository.Update(user);

            var res = new
            {
                Code = 1000,
                Data = user,
                Msg = "更新数据成功"
            };

            return JsonHelper.Serialize(res);

        }

        [HttpDelete("{id}")]
        public dynamic Dalete(int id)
        {

            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = string.Format("无法删除id为{0}的用户", id)
                };
            }

            _usersRepository.Delete(id);

            return new
            {
                Code = 1000,
                Data = "",
                Msg = "删除用户成功"
            };
        }


        [AllowAnonymous] //不需要验证也可访问当前请求
        //请求token
        [HttpPost, Route("token")]  //获取用户的Token。
        public dynamic GetToken(CreateUser newUser)
        {
            var username = newUser.Username.Trim();
            var password = newUser.Password.Trim();

            var user = _usersRepository.Table.Where(x => x.Username == username && x.Password == password).FirstOrDefault();

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不正确，请确认后重试"
                };
            }

            var token = ToKenHelper.GenerateToKen(_toKenParameter, user.Username);
            var refreshToken = "77585555";

            var res = new
            {
                Code = 1000,
                Data = new { Token = token, refreshToken = refreshToken },
                Msg = "用户登录成功"
            };

            //将结果实例化后输出
            return JsonHelper.Serialize(res);
        }

        [AllowAnonymous]
        [HttpPost, Route("refreshtoken")] //刷新Token
        public dynamic RefreshToken(RefreshTokenDTO refresh)
        {

            var user = ToKenHelper.ValidateToken(_toKenParameter, refresh);

            if (string.IsNullOrWhiteSpace(user))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "获取token验证失败，请重新返回登陆获取token"
                };
            }

            var token = ToKenHelper.GenerateToKen(_toKenParameter, user);
            var refreshToken = "77585555";
            return new
            {
                Code = 1000,
                Data = new { token = token, refreshToken = refreshToken },
                Msg = "刷新成功"
            };
        }

        [HttpPost, Route("query")]  //获取查询的数据。
        public dynamic GetQuery(Querys queryInfo)
        {   
            var querydata =  queryInfo.QueryDatas.ToString();
              
              /// <summary>
              /// 判断传输的值是否为空
              /// </summary>
              /// <returns></returns>
            if (string.IsNullOrWhiteSpace(querydata))
            {
                return new
                {
                    Code = 200,
                    Data = "",
                    Msg = "查询成功"
                };          
            }

            var user = _usersRepository.Table.Where(x => x.Username.Contains(querydata) || x.Remarks.Contains(querydata));

            // if (user.ToList().Count==0)
            // {
              
            // }

            //   分页
            // var u = user.Skip((currentPage - 1) * pageSize).Take(pageSize);

            var res = new
            {
                Code = 1000,
                Data = new
                {
                    Data = user
                    // Pager = new { currentPage, pageSize, totalSize = user.Count() }
                },
                Msg = "查询成功"
            };

            //将结果实例化后输出
            return JsonHelper.Serialize(res);
        }
    }

}